package com.hadron.remote 
{
	import flash.net.NetConnection;
	import flash.events.NetStatusEvent;
	import flash.net.Responder;
	import org.osflash.signals.natives.NativeSignal;
	import org.osflash.signals.Signal;
	/**
	 * ...
	 * @author Hadron
	 */
	public class RemoteConnectionService extends NetConnection
	{
		public var data:Object;  
        public var gatewayURL:String;  
        public var responder:Responder;  
   
		private var netStatus:NativeSignal;
		public var dataLoaded:Signal;
		public var dataReady:Signal;
		public var dataFault:Signal;
		
		public function RemoteConnectionService(gatewayURL:String, encoding:uint = 3) 
		{
			this.gatewayURL = gatewayURL;
			objectEncoding = encoding;
			
			if (gatewayURL)
			{
				connect(this.gatewayURL);
				responder = new Responder(handleResponseResult, handleResponseFault);
				netStatus = new NativeSignal(this, NetStatusEvent.NET_STATUS, NetStatusEvent);
				netStatus.add(handleNetEvent);
				
				// init signals
				dataLoaded = new Signal(Object);
				dataReady = new Signal(Object);
				dataFault = new Signal(Object);
			}
		}
		
		public function send(method:String, ... args):void
		{
			call.apply( null, [method, responder].concat(args));
		}
		
		private function handleNetEvent(e:NetStatusEvent):void
		{
			dataFault.dispatch(e.info.code);
		}
		
		private function handleResponseResult(data:Object):void
		{
			dataLoaded.dispatch(data);
			handleDataReady(data);
		}
		
		private function handleDataReady(data:Object):void
		{
			this.data = data;
			dataReady.dispatch(this.data);
		}
		
		private function handleResponseFault(data:Object):void
		{
			dataFault.dispatch(data);
		}
	}
}